// 全局变量声明
const API_URL = "/api/rest/self";

// ============ 登录状态校验 ============
if (localStorage.getItem('user') !== 'true') {
  alert('请先登录系统！');
  window.location.href = 'login.html';
  // 阻止后续代码执行
  throw new Error('未登录，已跳转');
}


const profileForm = document.getElementById('profile-form');

// 初始化部门选项
function initDept() {
    fetch('/api/rest/dept/all')
        .then((response) => response.json())
        .then((data) => {
            let selectElement = profileForm.querySelector('[name="deptId"]');
            data.forEach(item => {
                let option = document.createElement('option');
                option.value = item.id;
                option.innerText = item.name;
                selectElement.appendChild(option);
            });
        })
        .catch(error => {
            // 处理错误
            console.error('Error:', error);
        });
}

// 初始化角色选项
function initRole() {
    fetch('/api/rest/role/all')
        .then((response) => response.json())
        .then((data) => {
            let selectElement = profileForm.querySelector('[name="roleId"]');
            data.forEach(item => {
                let option = document.createElement('option');
                option.value = item.id;
                option.innerText = item.name;

                selectElement.appendChild(option);
            });
        })
        .catch(error => {
            // 处理错误
            console.error('Error:', error);
        });
}

function loadUserInfo() {
    // 获取当前用户信息
    fetch(API_URL)
        .then(response => response.json())
        .then(data => {
            // 填充表单数据
            document.getElementById('username').value = data.username;
            document.getElementById('name').value = data.name;
            document.getElementById('phone').value = data.phone;
            document.getElementById('email').value = data.email;
            document.getElementById('dept').value = data.dept.id;
            document.getElementById('role').value = data.role.id;
        })
        .catch(error => {
            console.error('获取用户信息失败:', error);
            showAlert('获取用户信息失败', 'danger', 'profile-alert');
        });
}

document.addEventListener('DOMContentLoaded', function() {
    initDept();
    initRole();
    // 加载用户信息
    loadUserInfo();
});


// 校验弹窗
function showAlert(message, type, alertId) {
    const alert = document.getElementById(alertId);
    // 检查元素是否存在
    if (!alert) {
        console.warn(`Alert element with id '${alertId}' not found`);
        return;
    }

    let alertMessage = document.createElement('div');
    alertMessage.className = `alert alert-${type} alert-dismissible fade show`;
    alertMessage.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    alert.appendChild(alertMessage);
    
    // 3秒后自动隐藏
    setTimeout(() => {
        alert.removeChild(alertMessage)
    }, 3000);
}

// 绑定用户信息表单提交事件
profileForm.addEventListener('submit', (event) => {
    event.preventDefault();
    
    // 先移除之前的验证状态
    profileForm.classList.remove('was-validated');
    
    if (profileForm.checkValidity()) {
        // 获取表单参数
        const form = event.target;
        const formData = new FormData(form);
        const userData = {};
        formData.forEach((value, key) => {
            userData[key] = value;
        });

        // 发送更新请求到后端
        fetch(API_URL, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(userData)
        }).then(response => {
                if (response.ok) {
                    Toastify({
                        text: "更新个人信息成功",
                        duration: 3000,
                        close: true,
                        backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
                        style: {
                            borderRadius: "10px"
                        }
                    }).showToast();
                } else {
                    return response.json().then(data => {
                        throw new Error(data.message || '更新失败');

                    });
                }
            }).catch(error => {
                console.error('更新失败:', error);
                showAlert(error.message || "个人信息更新失败", "danger", "profile-alert");
            });
    } else {
        profileForm.classList.add('was-validated');
    }
});

function previewAvatar(event) {
    const file = event.target.files[0];
    if (file) {
        // 验证文件类型
        if (!file.type.match('image.*')) {
            Toastify({
                text: "请选择有效的图片文件",
                backgroundColor: "#dc3545"
            }).showToast();
            return;
        }

        // 验证文件大小 (2MB)
        if (file.size > 10 * 1024 * 1024) {
            Toastify({
                text: "图片大小不能超过 10MB",
                backgroundColor: "#dc3545"
            }).showToast();
            return;
        }

        const formData = new FormData();
        formData.append('file', file);
        formData.append('type', '头像');
        fetch('/api/rest/attachment', {
            method: 'POST',
            body: formData
        }).then(response => response.json())
            .then(data => {
                console.log(data)
                document.getElementById('avatar').value = data.id
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('avatar-preview').src = data.url
                };
                reader.readAsDataURL(file);
            });
    }
}


const passwordForm = document.getElementById('password-form');

passwordForm.addEventListener('submit', (event) => {
    event.preventDefault();

    // 先移除之前的验证状态
    passwordForm.classList.remove('was-validated');

    if (passwordForm.checkValidity()) {
        // 获取密码表单数据
        const oldPassword = document.getElementById('oldPassword').value;
        const password = document.getElementById('newPassword').value;
        const passwordRepeat = document.getElementById('passwordRepeat').value;

        // 验证新密码和确认密码是否一致
        if (password !== passwordRepeat) {
            showAlert("新密码与确认密码不一致", "danger", "password-alert");
            passwordForm.classList.add('was-validated');
            return;
        }
        // 发送密码更新请求到后端
        fetch(API_URL + '/update-password', {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ oldPassword, password, passwordRepeat })
        })
            .then(response => {
                if (response.ok) {
                    Toastify({
                        text: "密码更新成功",
                        duration: 3000,
                        close: true,
                        backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
                        style: {
                            borderRadius: "10px"
                        }
                    }).showToast();
                } else {
                    return response.json().then(data => {
                        throw new Error(data.message || '密码更新失败');

                    });
                }
            }).catch(error => {
                console.error('密码更新失败:', error);
                showAlert(error.message || "密码更新失败", "danger", "password-alert");
            });
    } else {
        passwordForm.classList.add('was-validated');
    }
});

// 用户注销
function logout() {
    fetch('/api/rest/user/logout')
        .then(response => {
            if (response.ok) {
                localStorage.removeItem('user');
                window.location.href = '/login.html';
            }
        })
        .catch(error => {
            console.error('登出失败:', error);
        });
}